package org.example.interceptor;


import lombok.extern.slf4j.Slf4j;
import org.example.config.JwtConfig;
import org.example.constant.CodeEnum;
import org.example.exception.ServiceException;
import org.example.model.User;
import org.example.utils.CheckTokenUtil;
import org.example.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * jwt令牌校验的拦截器
 */
@Component
@Slf4j
public class JwtTokenUserInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtConfig jwtProperties;

    @Autowired
    private CheckTokenUtil checkTokenUtil;

    /**
     * 校验jwt
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }

        // 获取请求路径
        String requestURI = request.getRequestURI();

        // 放行登录请求，假设登录请求的路径是
        if (requestURI != null && ("/api/login/wechat".equals(requestURI) || requestURI.contains("/image"))) {
            return true;
        }

        //检查token是否过期
        if (checkTokenUtil.checkToken()){
            //Token过期
            throw new ServiceException(CodeEnum.UNAUTHORIZED);
        }
        //临时Token过期
        if (checkTokenUtil.checktemporaryToken()){

            throw new ServiceException(CodeEnum.UNAUTHORIZED);
        }
        User user = checkTokenUtil.checkUid();
        if(user == null)
        {
            throw new ServiceException(CodeEnum.UNAUTHORIZED);
        }
        ThreadLocalUtil.addCurrentUser(user);
        return true;
    }
}
